#include "TcpSocket.hpp"
#include "zh_CN.hpp"
#include <unordered_map>

std::unordered_map<std::string, std::string> reply_list;

const std::string normal_reply = "这憨批到底想说啥";

void InitList(){
  reply_list["我觉得"] = "我不要你觉得, 我要我觉得"; 
  reply_list["憨批"] = "你才是憨批!";
  reply_list["憨憨"] = "你欺负憨憨QAQ";
  reply_list["呵"] = "";
  reply_list["你好"] = "你也好, 你哪位?";
  reply_list["你谁"] = "叫我UDP服务器!";
  reply_list["可爱"] = "德莉傻才是世界第一可爱!";
  reply_list["贴贴"] = "你在想peach";
  reply_list["说"] = "我不听!";
  reply_list["QAQ"] = "锐雯连招?";
  reply_list["溜了"] = "你不在的日子里我会爱上别的女人";
  reply_list["鸡你太美"] = "你说话像蔡徐坤";
  reply_list["憨色"] = "你管这种人叫小天使?";
  reply_list["hanser"] = "别的地方刷hanser? 菊爆了";
  reply_list["无聊"] = "看来作业还是太少了";
  reply_list["嘤"] = "";
  reply_list["人"] = "我可能不是人, 但你是真的狗";
  reply_list["哼"] = "";
  reply_list["嘿"] = "";
  reply_list["哈"] = "";
  reply_list["画"] = "画仙子世界第一可爱!";
}

bool Reply(std::string& src, std::string& reply){
  for(const auto& str : reply_list){
    if(zh_CNIsInclude(src, str.first)){
      if(str.second.empty()){
        reply = src;
        reply += str.first;
        reply += str.first;
      }
      else{
        reply = str.second;
      }
      return true;
    }
  }
  return false;
}

int main(int argc, char* argv[]){
  if(argc < 3){
    printf("[ip] [port] Not Set\n");
    return 0;
  }
  InitList();
  std::string svr_ip = argv[1];
  uint16_t svr_port = atoi(argv[2]);
  TcpSocket Svr;
  if(!Svr.CreateSocket()){
    return 0;
  }
  if(!Svr.Bind(svr_ip, svr_port)){
    return 0;
  }
  if(!Svr.Listen()){
    return 0;
  }
  while(1){
    std::string recv_buf;
    sockaddr_in cli_addr;
    TcpSocket cli_sock;
    if(!Svr.Accept(cli_sock, cli_addr)){
      printf("Accept error!\n");
      continue;
    }
    printf("Client IP:%s port:%u\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
    while(1){
      if(!cli_sock.Recv(recv_buf)){
        printf("Client disconnect\n");
        break;
      }
      std::string reply;
      std::cout<<"client say:"<<recv_buf<<std::endl;
      if(Reply(recv_buf, reply)){
        cli_sock.Send(reply);
      }
      else{
        cli_sock.Send(normal_reply);
      }
    }
    cli_sock.Close();
  }
  Svr.Close();
  return 0;
}
